window.onload = () => {
  async function awaitTime(time) {
    return new Promise(r => setTimeout(r, time));
  }
  Vue.component('table-line', {
    // todo-item 组件现在接受一个
    // "prop"，类似于一个自定义 attribute。
    // 这个 prop 名为 todo。
    props: {
      id: Number,
      title: String,
      date: String,
      config: Object,
    },
    template: `<tr>
      <td>{{id}}</td>
      <td class="has-text-primary">{{title}}</td>
      <td>{{date}}</td>
      <td>{{countClick ? countClick : '未知'}}</td>
      <td>
        <button :class="{
          'button': true, 'is-primary': true, 'is-small ': true, 'is-loading': loading,
        }" @click="doit">开始</button>
      </td>
    </tr>`,
    data() {
      return {
        loading: false,
        countClick: 0,
      };
    },
    methods: {
      async doit() {
        const { id, config: {times, gaps} } = this;
        if (!id) return;
        let time = 1;
        const start = async () => {
          this.loading = true;
          try {
            await awaitTime(gaps);
            const result = await window.page.onStart(id);
            // console.log(result);
            this.countClick = result.countClick || 0;
            this.loading = false;
            if (time < times) {
              time += 1;
              start();
            }
          } catch (error) {
            console.log(error);
          }
        };
        start();
      },
    },
  });

  new Vue({
    el: '#app',
    data() {
      const date = new Date();
      return {
        name: '夏悦超',
        type: 'sec',
        gaps: 1,
        times: 30,
        loading: false,
        isReloadAlive: true,
        date: `${date.getFullYear()}年${date.getMonth()}月${date.getDate()}日`,
        list: [],
      };
    },
    computed: {
      config() {
        const { type = 'sec', gaps = 1, times = 5 } = this;
        let n = 1;
        if (type == 'sec') {
          n = 1;
        } else if (type == 'min') {
          n = 60;
        } else {
          n = 60 * 60;
        }
        return {
          gaps: gaps * n * 1000,
          times,
        }
      }
    },
    methods: {
      async onSearch() {
        const { name } = this;
        if (!name) return;
        try {
          this.loading = true;
          const list = await window.page.onSearch(name) || [];
          this.list = list;
          this.loading = false;
        } catch (error) {
          console.log(error);
        }
      },
      async reStart() {
        this.isReloadAlive = false;
        this.$nextTick(function(){
          this.isReloadAlive = true;
        });
        // this.isReloadAlive = true;
      }
    },
  })

  // document.getElementById('btn-search').addEventListener('click', async () => {
  //   const value = document.getElementById('text-input').value;
  //   console.log(value)
  //   const clickhandle = await window.page.onSearch(value);
  //   console.log('clickhandle', clickhandle)
  // })
}